package com.start.common.configs;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.start.common.enums.IntegerToEnumConvertFactory;
import com.start.common.enums.StringToEnumConvertFactory;
import com.start.common.jackson.StartEnumModule;
import com.start.common.jackson.StartJackDeserializersWrapper;
import com.start.common.jackson.StartJavaTimeModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;

@Configuration
public class StartWebMvcConfigurer implements WebMvcConfigurer {
    private static final String ASIA_SHANGHAI = "Asia/Shanghai";

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new IntegerToEnumConvertFactory());
        registry.addConverterFactory(new StringToEnumConvertFactory());
    }


    @Bean
    @Primary
    @ConditionalOnMissingBean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        StartJackDeserializersWrapper deserializers = new StartJackDeserializersWrapper();
        StartEnumModule startEnumModule = new StartEnumModule();
        startEnumModule.setDeserializers(deserializers);
        objectMapper.registerModule(startEnumModule);
        objectMapper.registerModule(new StartJavaTimeModule());
        return objectMapper;
    }

    /**
     * 避免form 提交 context-type 不规范中文乱码
     *
     * @return Filter
     */
    @Bean
    public OrderedCharacterEncodingFilter characterEncodingFilter() {
        OrderedCharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(StandardCharsets.UTF_8.name());
        filter.setForceEncoding(true);
        filter.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return filter;
    }

}
